package com.jysz.webcore.ssh.web.struts2;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.google.gson.Gson;
import com.google.gson.internal.StringMap;
import com.google.gson.reflect.TypeToken;
import com.jysz.webcore.utils.SshStringUtils;
import com.opensymphony.xwork2.ActionSupport;


/**
 *  通用的Action, 是所有Action的基类
 * @author kacarich email:javaengine@outlook.com
 *
 */
public class GenericAction extends ActionSupport {

	private static final long serialVersionUID = -910552223482404843L;
	
	private String contextPath; // 工程访问根路径
	
	private long actionExecTime = 0L; // action执行时间

    private String jsonText; // jsonText用于向页面暴漏
    
    private String redirectUrl;
    
    public static final String LOGIN_SESSION = "loginSession";

	public String getJsonText() {
        return jsonText;
    }
    public void setJsonText(String jsonText) {
        this.jsonText = jsonText;
    }

	public String getContextPath() {
		if (contextPath == null) {
			contextPath = getContextPath(getRequest());
		}
		return contextPath;
	}

	public void setContextPath(String contextPath) {
		this.contextPath = contextPath;
	}
	
	public String getContextPath(HttpServletRequest request) {
		return request == null ? "" : request.getContextPath();
	}
	
	public HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}
	
	public HttpServletResponse getResponse() {
		 return ServletActionContext.getResponse();  
	}
	
	public String toUtf8Encode(String s) {
		if(s == null) return null;
		else return SshStringUtils.toUtf8Encode(s);
	}
	
	public long getActionExecTime() {
		return (System.currentTimeMillis() - actionExecTime);
	}

	public void setActionExecTime(long actionExecTime) {
		this.actionExecTime = actionExecTime;
	}
	
	public Object getCurrentSession() {
		return getSessionAttribute(LOGIN_SESSION);
	}
	public void setCurrentSession(Object currentSession) {
		setSessionAttribute(LOGIN_SESSION, currentSession);
	}
	
	public void removeCurrentSession() {
		getSession().removeAttribute(LOGIN_SESSION);
	}
	
	public ServletContext getServletContext() {
		return ServletActionContext.getServletContext();
	}
	
	public void setSessionAttribute(String key, Object value) {
		getSession().setAttribute(key, value);
	}
	
	public Object getSessionAttribute(String key) {
		return getSession().getAttribute(key);
	}
	
	public HttpSession getSession() {
		return getRequest().getSession();
	}
	public String getRedirectUrl() {
		return redirectUrl;
	}
	public void setRedirectUrl(String redirectUrl) {
		this.redirectUrl = redirectUrl;
	}
	/**
	 * @param uri
	 * @param paramName url参数名字  paramName.name
	 * @param o
	 */
	public void setRedirectUrl(String uri,String paramName,Object o) {
		this.redirectUrl = buildParamStr(uri, paramName, o);
	}
	
	@SuppressWarnings("unchecked")
	private String buildParamStr(String uri,String searchObjName,Object o){
		
		if(searchObjName==null||o==null)
			return uri;
		StringBuilder sb=new StringBuilder(uri);
		Gson gson=new Gson();
		
		Map<String, Object> map=gson.fromJson(gson.toJson(o),
                new TypeToken<Map<String, Object>>() {}.getType());
		
		for(String s:map.keySet()){
			if(map.get(s).getClass().equals(StringMap.class)){
				build((StringMap<Object>) map.get(s), sb, searchObjName+"."+s);
			}else{
				if(map.get(s)!=null&&StringUtils.isNotEmpty(map.get(s).toString())){
					if(TypeToken.get(map.get(s).getClass()).toString().equals("java.lang.Double")){
						if(map.get(s).toString().endsWith(".0")){
							map.put(s, ((Double)map.get(s)).intValue());
						}
					}
					try {
						sb.append("&").append(searchObjName).append(".").append(s).append("=").append(URLEncoder.encode(map.get(s).toString(),"utf-8"));
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}
			}
		}
		
		return sb.toString();
	}
	
	@SuppressWarnings("unchecked")
	private void build(StringMap<Object> map,StringBuilder sb,String preStr){
		for(String s:map.keySet()){
			if(map.get(s).getClass().equals(StringMap.class)){
				preStr=preStr+"."+s;
				build((StringMap<Object>)map.get(s), sb,preStr);
			}else{
				if(map.get(s)!=null&&StringUtils.isNotEmpty(map.get(s).toString())){
					if(TypeToken.get(map.get(s).getClass()).toString().equals("java.lang.Double")){
						if(map.get(s).toString().endsWith(".0")){
							map.put(s, ((Double)map.get(s)).intValue());
						}
					}
					sb.append("&").append(preStr).append(".").append(s).append("=").append(map.get(s));
				}
			}
		}
		
	}
	
}
